<!--
@description ：创建/新增访客雷达
-->

<template>
  <div class="app-container">
    <div class="createVisitorRadarHeight" style="display: flex">
      <div class="text">{{ $route.query.flag == '1' ? '新增访客雷达' : '编辑访客雷达' }}</div>
      <div class="button">
        <el-button :loading="sureLoading" type="primary" @click="submitButton('form')">确定</el-button>
        <el-button @click="$router.go(-1)" :loading="sureLoading">取消</el-button>
      </div>
    </div>
    <div class="createVisitorRadarContent">
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="雷达名称" prop="radarName">
          <el-input v-model="form.radarName" clearable placeholder="请输入雷达名称" style="width: 600px"></el-input>
        </el-form-item>
        <el-form-item label="选择分组" prop="categoryId">
          <el-select v-model="form.categoryId" placeholder="请选择分组" style="width: 600px">
            <el-option v-for="item in groupList" :key="item.id" :label="item.name"
                       :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item class="showRedRules" label="文件类型" prop="mediaContentDetails">
          <RadarSelectMaterial v-if="operateFlag" :no-insurance.sync="noInsurance" :selectedList.sync="form.mediaContentDetails"
                               :show-tabs.sync="showTabs" @confirmSelect="confirmSelectFn"/>
        </el-form-item>
        <!--        <el-form-item label="跳转链接" prop="cccc">-->
        <!--          <el-input v-model="form.cccc" clearable placeholder="请输入跳转链接" style="width: 600px"></el-input>-->
        <!--        </el-form-item>-->
        <el-form-item label="雷达标题" prop="radarTitle">
          <el-input v-model="form.radarTitle" clearable placeholder="请输入名称，最长20字" style="width: 600px"></el-input>
        </el-form-item>
        <el-form-item label="雷达描述" prop="radarInfo">
          <el-input v-model="form.radarInfo" :rows="3" clearable maxlength="50" placeholder="请输入描述，最长50字"
                    show-word-limit
                    style="width: 600px" type="textarea"></el-input>
        </el-form-item>
        <el-form-item label="雷达封面图" required>
          <div class="upload">
            <el-upload
              :before-upload="beforeUploadImg"
              :show-file-list="false"
              action
              list-type="picture-card"
            >
              <i class="el-icon-plus"></i>
              <div slot="tip" class="el-upload__tip" style="color: #CCCCCC">
                建议上传800*800像素的图片，大小不超过10MB
              </div>
            </el-upload>
            <div v-for="(item, index) in imgs" :key="index" class="img" style="margin-left: 6px">
              <img v-if="item" :src="item" width="100%"/>
              <div class="imgPre">
                <i class="el-icon-zoom-in" @click="dialogVisible = true, dialogImageUrl = item"></i>
                <i class="el-icon-delete" @click="handleRemove(index)"></i>
              </div>
            </div>
          </div>
        </el-form-item>
        <el-form-item label="投放渠道" prop="scrmGetGuestSourceId">
          <el-select v-model="form.scrmGetGuestSourceId" placeholder="请选择投放渠道" style="width: 600px">
            <el-option v-for="item in scrmGetGuestSourceList" :key="item.scrmGetGuestSourceId"
                       :label="item.scrmGetGuestSourceName"
                       :value="item.scrmGetGuestSourceId"
            />
          </el-select>
        </el-form-item>
        <el-form-item class="switch-input" label="智能跟进" prop="shortLink">
          <el-switch v-model="form.shortLink" style="margin-right: 8px"></el-switch>
          转成短链
          <div v-if="form.shortLink && $route.query.flag != '1'" style="margin-left: 8px">
            {{ form.shortMaterialUrl }} <span style="color:#082aff;margin-left: 8px" v-if="form.shortMaterialUrl"
                                              @click="copyShortLink(form.shortMaterialUrl)">复制</span>
          </div>
        </el-form-item>
        <el-form-item class="switch-input" label="" prop="msgSend">
          <el-switch v-model="form.msgSend" style="margin-right: 8px"></el-switch>
          行为通知
          <div v-if="form.msgSend" style="margin-left: 8px">
            (当客户点击雷达且浏览率达到
            <el-input-number v-model="form.msgSendRate" :max="100" :min="0" :precision="0" :step="1"
                             clearable controls-position="right" placeholder="0"
                             style="width: 120px"></el-input-number>
            %时为高意向客户，发送雷达的员工将收到消息
          </div>
        </el-form-item>
        <el-form-item class="switch-input" prop="customerTagFlag">
          <el-switch v-model="form.customerTagFlag" style="margin-right: 8px"></el-switch>
          客户标签 (给点击雷达的客户打上选中的标签)
          <div v-if="form.customerTagFlag" style="margin-left: 8px">
            <tag-group v-model="form.customerTag" :show-crosswise.sync="showCrosswise"/>
          </div>
        </el-form-item>
      </el-form>
    </div>
    <el-dialog :close-on-click-modal="false" :visible.sync="dialogVisible" append-to-body title="图片预览"
               width="600px">
      <img :src="dialogImageUrl" alt="" width="100%">
    </el-dialog>
  </div>
</template>
<script>
import RadarSelectMaterial from "@/components/radarSelectMaterial.vue";
import {uploadImgFile} from "@/api/communityOperating/fileManage";
import tagGroup from "@/components/tagGroup.vue";
import {categoryList} from "@/api/article/group";
import {addVisitorRadar, queryRadarInfo, querySourceId, updateRadarInfo} from "@/api/visitorRadar";

export default {
  name: "createVisitorRadar", //新增/编辑 访客雷达
  props: {},
  components: {
    tagGroup,
    RadarSelectMaterial,
  },
  data() {
    return {
      form: {
        mediaContentDetails: [],
        categoryId: '',
        radarName: '',
        radarTitle: '',
        radarInfo: '',
        scrmGetGuestSourceId: '',
        shortLink: true,
        msgSend: true,
        msgSendRate: '',
        customerTag: [],
        customerTagFlag: true,
        shortMaterialUrl: '',
      },
      rules: {
        radarName: [{required: true, message: '雷达名称不能为空', trigger: 'blur'},{
          max: 20, message: "雷达名称在20字内，请核对后再输入", trigger: "blur"
        }],
        categoryId: [{required: true, message: '分组不能为空', trigger: 'change'}],
        radarTitle: [{required: true, message: '雷达标题不能为空', trigger: 'blur'},
          {
            max: 20, message: "名称输入有误，请重新输入", trigger: "blur"
          }
        ],
        radarInfo: [{required: true, message: '雷达描述不能为空', trigger: 'blur'},{
          max: 20, message: "内容输入有误，请重新输入", trigger: "blur"
        }],
        scrmGetGuestSourceId: [{required: true, message: '投放渠道不能为空', trigger: 'change'}],
      },
      scrmGetGuestSourceList: [],
      groupList: [], //分组
      imgs: [],
      showTabs: false,
      noInsurance: false,
      sureLoading: false,
      dialogVisible: false,
      dialogImageUrl: '',
      showCrosswise: true,
      operateFlag: '',
    }
  },
  watch: {},
  methods: {
    confirmSelectFn(val) {
      this.form.mediaContentDetails = val;
    },
    // 确认
    submitButton() {
      if (this.form.mediaContentDetails.length == 0) return this.$message.error('请选择文件类型')
      if (this.imgs.length == 0) return this.$message.error('请上传雷达封面图')
      if (this.form.msgSend && !this.form.msgSendRate) return this.$message.error('请输入浏览率')
      if (this.form.customerTagFlag && this.form.customerTag.length == 0) return this.$message.error('请添加标签')
      this.$refs.form.validate(valid => {
        if (valid) {
          this.sureLoading = true
          let params = {
            ...this.form,
            radarId: this.$route.query.id || '',
            mediaInfo: JSON.stringify(this.form.mediaContentDetails[0]),
            radarImage: this.imgs[0],
            shortLink: this.form.shortLink ? '1' : '0',
            msgSend: this.form.msgSend ? '1' : '0',
            customerTagFlag: this.form.customerTagFlag ? '1' : '0',
          }
          if (this.$route.query.id) {
            updateRadarInfo(params).then(res => {
              if (res.code == 200) {
                this.$message.success('编辑成功')
                this.$router.go(-1)
              }
              this.sureLoading = false
            }).catch(() => {
              this.sureLoading = false
            })
          } else {
            addVisitorRadar(params).then(res => {
              if (res.code == 200) {
                this.$message.success('新增成功')
                this.$router.go(-1)
              }
              this.sureLoading = false
            }).catch(() => {
              this.sureLoading = false
            })
          }
        }
      })
    },
    // 图片上传
    async beforeUploadImg(img) {
      console.log(img)
      const type = ['image/png', 'image/jpg', 'image/gif', 'image/jpeg']
      const isJPG = type.includes(img.type)
      const isLt10M = img.size / 1024 / 1024 < 10

      if (!isJPG) {
        this.$message.error('上传图片支持jpg、png、gif格式!')
      } else if (!isLt10M) {
        this.$message.error('您上传的文件超过10MB!')
      } else {
        console.log(img, '====img')
        const formData = new FormData()
        formData.append('file', img)
        const {data} = await uploadImgFile(formData)
        this.imgs = [window.globalConfig.IMAGE_API + data.url]
        console.log(this.imgs[0])
        this.form.photoName = data.photoName
        this.form.photoUrl = data.url
      }
    },
    // 图片删除
    handleRemove(index) {
      this.imgs.splice(index, 1)
    },
    // 短链复制
    copyShortLink(val) {
      navigator.clipboard.writeText(val).then(() => {
        this.$message({message: '复制成功', type: 'success'})
      });
    },
  },
  mounted() {
    categoryList({levelType: '0', mediaType: '12'}).then(res => {
      this.groupList = res.data || []
    })
    querySourceId().then(res => {
      this.scrmGetGuestSourceList = res.data || []
    })
    if (this.$route.query.id) {
      queryRadarInfo({radarId: this.$route.query.id}).then(res => {
        this.form = {
          ...res.data,
          mediaContentDetails: res.data.mediaInfo ? [JSON.parse(res.data.mediaInfo)] : [],
          customerTag: res.data.customerTag? JSON.parse(res.data.customerTag) : [],
          shortLink: res.data.shortLink == '1' ? true : false,
          msgSend: res.data.msgSend == '1' ? true : false,
          customerTagFlag: res.data.customerTagFlag == '1' ? true : false,
          shortMaterialUrl: res.data?.shortMaterialUrl ? window.globalConfig.SHARE_SHORT_LINK + res.data.shortMaterialUrl : ''
        }
        this.$set(this, 'form', this.form)
        this.imgs = [res.data.radarImage || '']
        this.operateFlag = '1'
      }).catch(() => {
        this.operateFlag = '1'
      })
    }else{
      this.operateFlag = '1'
    }
  },
  created() {
  },
}

</script>

<style lang="scss" scoped>

.app-container {
  height: 100%;
  padding: 0;

  .createVisitorRadarHeight {
    align-items: center;
    justify-content: space-between;
    margin-bottom: 16px;
    background-color: white;
    height: 60px;
    padding-left: 20px;
    padding-right: 20px;
    border-radius: 6px;

    .text {
      font-size: 20px;
    }
  }

  .createVisitorRadarContent {
    background-color: white;
    border-radius: 6px;
    padding: 10px 0;
  }
}


.img {
  position: relative;
  width: 148px;
  height: 148px;
  margin-right: 10px;

  img {
    height: 100%;
  }

  .imgPre {
    width: 100%;
    height: 100%;
    position: absolute;
    top: 0;
    left: 0;
    background: rgba(238, 238, 238, 0.4);
    display: flex;
    justify-content: space-around;
    align-items: center;
    opacity: 0;

    &:hover {
      opacity: 1;
    }

    i {
      font-size: 22px;
      color: #fff;
    }
  }
}

.upload {
  display: flex;
}

.switch-input {
  padding: 4px 0 0 10px !important;

  ::v-deep.el-form-item__content {
    line-height: 30px;
    display: flex;
    align-items: center;
  }
}

// 必录框前面的 '*'
.showRedRules {
  ::v-deep.el-form-item__label:before {
    content: '*';
    color: #e74e59;
    margin-right: 4px;
  }
}
</style>
